<template>
  <div class="departments">
    <el-card>
      <template #header>
        <div>组织架构</div>
      </template>
      <div style="width: 80%; margin: 0 auto">
        <!-- 抽离出item项
        1：只用于当前模块的组件 当前模块下components/组件名.vue   如果会多次使用  src/component下
        -->
        <TreeItem :item="topInfo" style="width: 100%" @getData="getData" />
        <hr>
        <el-tree
          :data="treeData"
          :props="{ label: 'name', children: 'children' }"
        >
          <template v-slot="{ data }">
            <TreeItem :item="data" style="width: 100%" @getData="getData" />
          </template>
        </el-tree>
      </div>
    </el-card>
    <!-- 新增弹框组件 -->
    <Add :init-tree-data="initTreeData" @getData="getData" />
  </div>
</template>
<script>
import { companyDepartment } from '@/api/departments.js'
// 1:导入  2：注册  3：使用
import TreeItem from './components/treeItem.vue'
import Add from './components/add.vue'
export default {
  components: {
    TreeItem,
    Add
  },
  data() {
    return {
      treeData: [],
      initTreeData: [], // 原始树形结构数据
      topInfo: {
        name: '传智',
        manager: '负责人',
        id: '',
        top: true // 顶部数据
      }
    }
  },
  created() {
    this.getData()
  },
  methods: {
    async getData() {
      const res = await companyDepartment()
      this.topInfo.name = res.data.companyName
      this.initTreeData = res.data.depts
      this.treeData = this.changeData(res.data.depts, '')
      // console.log('组织架构', res)
    },
    changeData(arr, str = '') {
      return arr.filter((item) => {
        if (item.pid === str) {
          item.children = this.changeData(arr, item.id)
          return true
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.departments {
  padding: 15px;
}
</style>
